import { CoreConst, HttpError } from '@ibiz-template/core';
// import { clearCookie, getCookie, setCookie } from 'qx-util';
import { IAuthService, IAuthInfo, IAuthResult } from '../../../interface';

/**
 * 认证服务
 *
 * @author chitanda
 * @date 2022-07-19 18:07:51
 * @export
 * @class AuthService
 */
export class V7AuthService implements IAuthService {
  get isAnonymous(): boolean {
    // return getCookie(CoreConst.IS_ANONYMOUS) === '1';
    return false
  }

  /**
   * 使用匿名账号登录
   *
   * @author tony001
   * @date 2024-05-14 17:05:47
   * @return {*}  {Promise<boolean>}
   */
  async anonymousLogin(): Promise<boolean> {
    const { anonymousUser, anonymousPwd } = ibiz.env;
    if (!anonymousUser || !anonymousPwd) {
      ibiz.log.error(ibiz.i18n.t('runtime.service.noFoundUsernamePassword'));
      return false;
    }
    const result = await this.login(anonymousUser, anonymousPwd);
    if (result) {
      // setCookie(CoreConst.IS_ANONYMOUS, '1', 0, true);

      // // 全部改成session级别的
      // const token = getCookie(CoreConst.TOKEN)!;
      // const expirein = getCookie(CoreConst.TOKEN_EXPIRES)!;
      // const remember = getCookie(CoreConst.TOKEN_REMEMBER)!;
      // const refreshToken = getCookie(CoreConst.REFRESH_TOKEN)!;
      // setCookie(CoreConst.TOKEN, token, 0, true);
      // setCookie(CoreConst.TOKEN_EXPIRES, expirein, 0, true);
      // setCookie(CoreConst.TOKEN_REMEMBER, remember, 0, true);
      // if (refreshToken) {
      //   setCookie(CoreConst.REFRESH_TOKEN, refreshToken, 0, true);
      // }
    }
    return result;
  }

  /**
   * 登录
   *
   * @author tony001
   * @date 2024-05-14 17:05:54
   * @param {string} loginName
   * @param {string} password
   * @param {boolean} [remember]
   * @param {IData} [headers]
   * @return {*}  {Promise<boolean>}
   */
  async login(
    loginName: string,
    password: string,
    remember?: boolean,
    headers?: IData,
  ): Promise<boolean> {
    // eslint-disable-next-line no-useless-catch
    try {
      this.clearAuthData();
      const res = await ibiz.net.post(
        '/v7/login',
        {
          loginname: loginName,
          password,
          rememberme: remember,
        },
        {},
        headers,
      );
      const { data } = res;
      if (data && data.token) {
        const cacheDay = remember ? 30 : 0;
        // if (remember) {
        //   setCookie(CoreConst.TOKEN_REMEMBER, '1', cacheDay, true);
        // }
        // setCookie(CoreConst.TOKEN, data.token, cacheDay, true);
        // const expiredDate =
        //   new Date().getTime() + (data.expirein || 7199) * 1000;
        // setCookie(CoreConst.TOKEN_EXPIRES, `${expiredDate}`, cacheDay, true);
        // if (data.refresh_token) {
        //   setCookie(
        //     CoreConst.REFRESH_TOKEN,
        //     data.refresh_token,
        //     cacheDay,
        //     true,
        //   );
        // }
        // clearCookie(CoreConst.IS_ANONYMOUS);
      }
      return true;
    } catch (err: unknown) {
      ibiz.notification.error({
        title: ibiz.i18n.t('runtime.service.loginFailure'),
        desc: (err as HttpError).message || '',
      });
    }
    return false;
  }

  /**
   * 登出
   *
   * @author tony001
   * @date 2024-05-14 17:05:04
   * @return {*}  {Promise<boolean>}
   */
  async logout(): Promise<boolean> {
    try {
      await ibiz.net.get('/v7/logout');
      this.clearAuthData();
      return true;
    } catch (err: unknown) {
      ibiz.notification.error({
        title: ibiz.i18n.t('runtime.service.logoutFailure'),
        desc: (err as HttpError).message || '',
      });
    }
    return false;
  }

  /**
   * 变更密码
   *
   * @author tony001
   * @date 2024-05-14 17:05:22
   * @param {string} oldPwd
   * @param {string} newPwd
   * @return {*}  {Promise<IAuthResult>}
   */
  async changePwd(oldPwd: string, newPwd: string): Promise<IAuthResult> {
    try {
      const res = await ibiz.net.post('/uaa/changepwd', {
        oldPwd,
        newPwd,
      });
      return { ok: true, result: res };
    } catch (err: unknown) {
      return { ok: false, result: err as IData };
    }
  }

  /**
   * 页面未关闭情况下，自动延长登录时间
   *
   * @author tony001
   * @date 2024-05-14 17:05:38
   * @return {*}  {Promise<void>}
   */
  async extendLogin(): Promise<void> {
    if (this.isAnonymous) {
      // 匿名登录不需要延长都是会话级的
      return;
    }

    // const token = getCookie(CoreConst.TOKEN);
    // const expirein = getCookie(CoreConst.TOKEN_EXPIRES);
    // if (token && expirein) {
    //   // 计算到过期时间所需的延时毫秒数，预留提前量
    //   let wait = Number(expirein) - new Date().getTime();
    //   const early = 5 * 60 * 1000;
    //   wait = wait > early ? wait - early : 0;
    //   setTimeout(async () => {
    //     const remember = getCookie(CoreConst.TOKEN_REMEMBER);
    //     const refreshToken = getCookie(CoreConst.REFRESH_TOKEN);
    //     const cacheDay = remember ? 30 : 0;
    //     let res;
    //     if (refreshToken != null && refreshToken !== '') {
    //       res = await ibiz.net.get(`/uaa/refresh_token/${refreshToken}`);
    //     } else {
    //       res = await ibiz.net.get(`/uaa/refreshtoken2`);
    //     }
    //     if (res.ok) {
    //       if (remember) {
    //         setCookie(CoreConst.TOKEN_REMEMBER, '1', cacheDay, true);
    //       }
    //       setCookie(CoreConst.TOKEN, res.data.token, cacheDay, true);
    //       const expiredDate =
    //         new Date().getTime() + (res.data.expirein || 7199) * 1000;
    //       setCookie(CoreConst.TOKEN_EXPIRES, `${expiredDate}`, cacheDay, true);
    //       if (res.data.refresh_token) {
    //         setCookie(
    //           CoreConst.REFRESH_TOKEN,
    //           res.data.refresh_token,
    //           cacheDay,
    //           true,
    //         );
    //       }
    //       // token刷新后，更新 appData
    //       await this.loadAppData();
    //       // 刷新token之后用新的token重连mqtt
    //       ibiz.hub.getAllApps().forEach(app => {
    //         app.initMqtt();
    //       });
    //     }
    //     // 下一次延时做准备
    //     this.extendLogin();
    //   }, wait);
    // }
  }

  /**
   * 通过refreshToken换算token
   *
   * @author tony001
   * @date 2024-05-14 17:05:45
   * @return {*}  {Promise<void>}
   */
  async refreshToken(): Promise<void> {
    // const remember = getCookie(CoreConst.TOKEN_REMEMBER);
    // const refreshToken = getCookie(CoreConst.REFRESH_TOKEN);
    // if (refreshToken != null && refreshToken !== '') {
    //   const res = await ibiz.net.get(`/uaa/refresh_token/${refreshToken}`);
    //   if (res.ok) {
    //     const cacheDay = remember ? 30 : 0;
    //     if (remember) {
    //       setCookie(CoreConst.TOKEN_REMEMBER, '1', cacheDay, true);
    //     }
    //     setCookie(CoreConst.TOKEN, res.data.token, cacheDay, true);
    //     const expiredDate =
    //       new Date().getTime() + (res.data.expirein || 7199) * 1000;
    //     setCookie(CoreConst.TOKEN_EXPIRES, `${expiredDate}`, cacheDay, true);
    //     if (res.data.refresh_token) {
    //       setCookie(
    //         CoreConst.REFRESH_TOKEN,
    //         res.data.refresh_token,
    //         cacheDay,
    //         true,
    //       );
    //     }
    //     clearCookie(CoreConst.IS_ANONYMOUS);
    //   }
    // }
  }

  /**
   * 获取当前环境的权限信息（无登录则返回undefined）
   *
   * @author tony001
   * @date 2024-05-14 17:05:57
   * @return {*}  {(IAuthInfo | undefined)}
   */
  getAuthInfo(): IAuthInfo | undefined {
    // const token = getCookie(CoreConst.TOKEN);
    // const isAnonymous = !!getCookie(CoreConst.IS_ANONYMOUS);
    // return token
    //   ? {
    //       token,
    //       isAnonymous,
    //     }
    //   : undefined;
    return
  }

  /**
   * 加载应用数据
   *
   * @author chitanda
   * @date 2022-07-20 20:07:50
   * @return {*}  {Promise<void>}
   */
  protected async loadAppData(): Promise<void> {
    const res = await ibiz.net.get('/appdata');
    if (res.ok) {
      ibiz.appData = res.data;
    }
  }

  /**
   * 清空权限数据
   *
   * @author tony001
   * @date 2024-05-14 17:05:18
   * @protected
   */
  protected clearAuthData(): void {
    // clearCookie(CoreConst.TOKEN);
    // clearCookie(CoreConst.TOKEN_EXPIRES);
    // clearCookie(CoreConst.TOKEN_REMEMBER);
    // clearCookie(CoreConst.REFRESH_TOKEN);
    // clearCookie(CoreConst.IS_ANONYMOUS);
    ibiz.appData = undefined;
    ibiz.orgData = undefined;
  }
}
